#include <iostream>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8081
#define BUFFER_SIZE 1024

int main() {
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        perror("Socket creation error");
        return 1;
    }

    struct sockaddr_in serv_addr;
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);
    
    if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
        perror("Invalid address");
        return 1;
    }

    if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("Connection failed");
        return 1;
    }

    std::cout << "Connected to server" << std::endl;

    while (true) {
        std::cout << "Enter English text (q to quit): ";
        std::string input;
        std::getline(std::cin, input);

        if (input == "q") break;

        send(sock, input.c_str(), input.size(), 0);
        std::cout << "Sent: " << input << std::endl;

        char buffer[BUFFER_SIZE] = {0};
        int valread = read(sock, buffer, BUFFER_SIZE);
        if (valread < 0) {
            perror("Read error");
            break;
        } else if (valread == 0) {
            std::cout << "Server closed connection" << std::endl;
            break;
        }

        std::string response(buffer, valread);
        std::cout << "Received: " << response << std::endl;
    }

    close(sock);
    return 0;
}